 
package com.whmskj.xjlhsc.mobie.energymanage.service.impl;

import com.whmskj.xjlhsc.mobie.energymanage.mapper.MobileDashboardMapper;
import com.whmskj.xjlhsc.mobie.energymanage.service.MobileDashboardService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;
import java.util.Map;

@Service
public class MobileDashboardServiceImpl implements MobileDashboardService {
	
	@Resource
	private MobileDashboardMapper dashboardMapper;
	
	@Override
	public Map<String, Object> getDefaultGlobalEnergySummary() {
		Map<String, Object> summary = dashboardMapper.getDefaultGlobalEnergySummary();
		if (summary != null) {
			String[] keys = {"todayTotalKwh", "yesterdayTotalKwh", "currentMonthTotalKwh", "lastMonthTotalKwh"};
			for (String key : keys) {
				Object v = summary.get(key);
				if (v instanceof Number) {
					double wan = ((Number) v).doubleValue() / 10000.0d;
					summary.put(key, Math.round(wan * 10000.0d) / 10000.0d);
				}
			}
		}
		return summary;
	}
	
	@Override
	public Map<String, Object> getGlobalEnergySummary(LocalDate day, String process, Integer collectFlag) {
		if (day == null) {
			day = LocalDate.now();
		}
		return dashboardMapper.getGlobalEnergySummary(day, process, collectFlag);
	}

    @Override
    public List<Map<String, Object>> getDeviceList(LocalDate day, String process, String keyword, Integer collectFlag) {
        if (day == null) {
            day = LocalDate.now();
        }
        List<Map<String, Object>> result = dashboardMapper.getDeviceList(day, process, keyword, collectFlag);
        // 格式化所有数值为两位小数
        result.forEach(this::formatNumbers);
        return result;
    }

    	@Override
	public List<Map<String, Object>> getDefaultDeviceStatusStats() {
		return dashboardMapper.getDefaultDeviceStatusStats();
	}
	
	@Override
	public List<Map<String, Object>> getDeviceStatusStats(String process) {
		return dashboardMapper.getDeviceStatusStats(process);
	}

    /**
     * 格式化Map中的所有数值为两位小数
     */
    private void formatNumbers(Map<String, Object> data) {
        if (data == null) return;

        data.forEach((key, value) -> {
            if (value instanceof Number) {
                // 数值类型保留两位小数
                if (value instanceof Double || value instanceof Float) {
                    data.put(key, Math.round(((Number) value).doubleValue() * 100.0) / 100.0);
                }
            } else if (value instanceof Map) {
                // 递归处理嵌套的Map（如realtime数据）
                formatNumbers((Map<String, Object>) value);
            }
        });
    }



}